<template>
    <el-upload
            ref="upload"
            :class="[{hideUpload: (disable || (modelValue && Array.isArray(modelValue) && modelValue.length >= limit)), hideUploadTip: disable}]"
            :limit="limit"
            :multiple="multiple"
            :list-type="listType"
            v-model:file-list="temp"
            :before-upload="fileBeforeUpload"
            :on-success="fileUploadSucc"
            :on-error="fileUploadErr"
            :http-request="fileUpload">
        <template #tip>
            <div class="el-upload__tip" v-if="tip">{{tip}}</div>
        </template>

        <template #trigger>
            <el-button size="small" type="primary" v-if="isText">点击上传</el-button>
            <el-icon v-if="isCard"><Plus /></el-icon>
        </template>
        <!--<i class="el-icon-plus" v-if="isCard"></i>-->

        <template v-slot:file="{file}">
            <template v-if="isText">
                <div>
                    <a :href="file.url" target="_blank" class="el-upload-list__item-name"><i
                            class="el-icon-document"></i><span>{{file.name}}</span></a>
                    <label class="el-upload-list__item-status-label">
                        <el-icon class="el-icon--upload-success el-icon--circle-check">
                            <CircleCheck />
                        </el-icon>
                    </label>
                    <el-icon class="el-icon--close"
                            @click="fileUploadRemove(file)"
                             v-if="!disable"><Close /></el-icon>
                    <el-progress
                            v-if="file.status === 'uploading'"
                            :type="isCard ? 'circle' : 'line'"
                            :stroke-width="isCard ? 6 : 2"
                            :percentage="parsePercentage(file.percentage)">
                    </el-progress>
                    <!--<i class="el-icon-close-tip">按 delete 键可删除</i>-->
                </div>
            </template>
            <template v-else-if="isCard">
                <img class="el-upload-list__item-thumbnail"
                     alt="" :data-value="file.id" :src="fileTypeIcon(file)">
                <label class="el-upload-list__item-status-label ">
                    <el-icon class="el-icon--upload-success el-icon--check">
                        <Check />
                    </el-icon>
                </label>
                <el-progress
                        v-if="file.status === 'uploading'"
                        :type="isCard ? 'circle' : 'line'"
                        :stroke-width="isCard ? 6 : 2"
                        :percentage="parsePercentage(file.percentage)">
                </el-progress>
                <div class="el-upload-list__item-actions">
          <span v-if="isPreview || isPic(file)"
                class="el-upload-list__item-preview"
                @click="handlePicturePreview(file)">
            <el-icon class="el-icon-zoom-in"></el-icon>
          </span>
                    <span class="el-upload-list__item-delete"
                          @click="handleDownload(file)"
                    >
            <el-icon><Download /></el-icon>
          </span>
                    <span v-if="!disable"
                          class="el-upload-list__item-delete"
                          @click="handleCardRemove(file)"
                    >
            <el-icon><Delete /></el-icon>
          </span>
                </div>
            </template>
        </template>
    </el-upload>

    <!--<el-upload-->
    <!--list-type="picture-card"-->
    <!--:class="{hideUpload: true || row.laborContractList.length === 10}"-->
    <!--multiple="true"-->
    <!--limit="10"-->
    <!--:accept="UploadFileType.image"-->
    <!--:disabled="true"-->
    <!--:file-list="row.laborContractFileList"-->
    <!--:on-preview="handlePictureCardPreview"-->
    <!--:on-success="(response, file, fileList) => fileUploadSucc(response, file, fileList, row, 2)"-->
    <!--:on-error="(response, file, fileList) => fileUploadErr(response, file, fileList, row, 2)"-->
    <!--:on-remove="(file, fileList) => fileUploadRemove(file, fileList, row, 2)"-->
    <!--:http-request="(file)=>fileUpload(file)">-->
    <!--<i class="el-icon-plus"></i>-->
    <!--</el-upload>-->

</template>

<script>
    import { reactive } from 'vue'
    import {upload} from "@/api/tool/file";
    import {downloadFileBlob} from "@/utils/util";

    export default {
        name: "upload",
        emits: ['update:modelValue'],
        props: {
            // 表单对象
            modelValue: {
                type: [Array, Object],
                default: function () {
                    return {}
                }
            },
            // 文件上传类型
            listType: {
                type: String,
                default: "text"
                // picture-card 图片列表
                // picture  单个图片
            },
            // 限制数量
            limit: {
                type: Number,
                default: 10000
            },
            // 详情
            disable: {
                type: Boolean,
                default: false
            },
            // 文件最大尺寸(MB)
            fileMaxSize: {
                type: Number,
                default: 100
            },
            // 接收文件类型
            accept: {
                type: String,
                default: ""
            },
            // 是否多选
            multiple: {
                type: [Boolean, String],
                default: false
            },
            // 提示内容
            tip: {
                type: String,
                default: ""
            },
            isPublic: {
                type: Boolean,
                default: false
            },
            isPreview: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                refName: "",
                temp: [],
                isUploadRefresh: false,
                isUserUploadFlag: false,
            };
        },
        watch: {
            modelValue: {
                handler(val) {
                    this.obtainTempData(val);
                },
                immediate: true
            }
        },
        computed: {
            isText() {
                return this.listType === "text";
            },
            isCard() {
                return this.listType === "picture-card"
            },
            fileTypeIcon: function () {
                return (item) => {
                    const file = "/img/file/file.png";
                    const zip = "/img/file/package.png";
                    const docx = "/img/file/docx.png";
                    const ppt = "/img/file/ppt.png";
                    const xlsx = "/img/file/xlsx.png";
                    const pdf = "/img/file/pdf.png";
                    const name = item.name;
                    if (name) {
                        const suffix = name.substring(name.lastIndexOf(".") + 1).toLocaleUpperCase();
                        if (["JPG", "JPEG", "PNG"].includes(suffix)) {
                            return item.url;
                        } else if (["DOCX", "DOC"].includes(suffix)) {
                            return docx;
                        } else if (["PPT"].includes(suffix)) {
                            return ppt;
                        } else if (["XLS", "XLSX"].includes(suffix)) {
                            return xlsx;
                        } else if (["PDF"].includes(suffix)) {
                            return pdf;
                        } else if (["ZIP", "RAR", "TAR", "7Z"].includes(suffix)) {
                            return zip;
                        }
                    }
                    return file;
                }
            },
            isPic: function () {
                return (item) => {
                    const name = item.name;
                    if (name) {
                        const suffix = name.substring(name.lastIndexOf(".") + 1).toLocaleUpperCase();
                        if (["JPG", "JPEG", "PNG"].includes(suffix)) {
                            return true;
                        } else {
                            return false
                        }
                    }
                    return false;
                }
            }
        },
        mounted() {
            // this.obtainTempData(this.value);
        },
        methods: {
            parsePercentage(val) {
                return parseInt(val, 10);
            },
            obtainTempData(val) {
                if (this.isText || this.isCard) {
                    if (val && Array.isArray(val)) {
                        if (!this.isUploadRefresh) {
                            this.temp = reactive(val);
                        }
                        this.isUploadRefresh = false
                    } else {
                        this.temp = val ? [val] : [];
                    }
                }
            },
            getFileList() {
                let list = [];
                if (this.isText || this.isCard) {
                    if (!this.modelValue) {
                        this.modelValue = [];
                    }
                    list = this.modelValue;
                }
                return list;
            },

            fileBeforeUpload(file) {
                if (this.fileMaxSize && this.fileMaxSize > 0) {
                    const isLt4M = file.size / 1024 / 1024 <= this.fileMaxSize;
                    if (!isLt4M) {
                        this.$message.error('上传文件大小不能超过 ' + this.fileMaxSize + 'MB!');
                        return false;
                    }
                }
                return true;
            },
            fileUpload(options) {
                const file = options.file;
                const isPublic = this.isPublic ? "true" : "false";
                this.isUserUploadFlag = true;
                return upload(file, isPublic, options.onProgress)
                // return new Promise((r, j)=> {
                //   upload(file, isPublic, options.onProgress).then(r=> {
                //     j()
                //   }, r => j())
                // })
            },
            fileUploadSucc(rsp, file, fileList) {
                if (rsp) {
                    let data = rsp.data;
                    if (data.code === 200 && data.success) {
                        data = data.data;
                        file.id = data.id;
                        this.$message.success("上传成功");

                        let index = 0;
                        for (let i in fileList) {
                            if (fileList[i].id === file.id) {
                                index = i;
                                break;
                            }
                        }

                        let list = this.getFileList();
                        this.isUploadRefresh = true;
                        list.splice(index, 0, {
                            id: data.id,
                            name: data.name,
                            url: data.url,
                        });

                        // this.temp.push(file);
                        this.$emit("update:modelValue", list);
                    }
                }
            },
            fileUploadErr(rsp, file, fileList) {
                this.$message.error("上传失败")
            },
            fileUploadRemove(file) {
                // const fileList = this.$refs.upload.uploadFiles || [];
                // if (this.isText && !!fileList && fileList.length > 0) {
                //     for (let i = 0; i < fileList.length; i++) {
                //         const item = fileList[i];
                //         if (file.id === item.id) {
                //           console.log(item)
                //           fileList.splice(i, 1);
                //             break;
                //         }
                //     }
                // }
                let list = this.getFileList();
                let index = -1;
                for (let i = 0; i < list.length; i++) {
                    const item = list[i];
                    if (file.id === item.id) {
                        this.isUploadRefresh = true;
                        list.splice(i, 1);
                        index = i;
                        break;
                    }
                }
                if (index > -1 && this.isText && this.isUserUploadFlag) {
                    this.$refs.upload.handleRemove(file)
                  // console.log(this.$refs);
                  //   const parent = this.$refs.upload.$children[1].$el;
                  //   parent.removeChild(parent.childNodes[index]);
                }
            },
            handleCardRemove(file) {
                let list = this.getFileList();
                for (let i = 0; i < list.length; i++) {
                    const item = list[i];
                    if (file.id === item.id) {
                        this.isUploadRefresh = true;
                        list.splice(i, 1);
                        break;
                    }
                }
                for (let i = 0; i < this.temp.length; i++) {
                    const item = this.temp[i];
                    if (file.id === item.id) {
                        this.isUploadRefresh = true;
                        this.temp.splice(i, 1);
                        break;
                    }
                }
                this.$refs.upload.handleRemove(file);
            },
            // 预览
            handlePicturePreview(file) {
                if (this.isPreview) {
                    this.$emit("preview", file);
                } else {
                    this.$ImagePreview([{url: file.url}], 0, {
                        closeOnClickModal: true,
                        beforeClose: () => {

                        }
                    });
                }
            },
            // 下载
            handleDownload(file) {
                downloadFileBlob(file.url, file.name);
                // const aLink = document.createElement('a');
                // aLink.download=file.name;
                // aLink.target = "_blank";
                // aLink.href = file.url;
                // aLink.click();
            },
        }
    };
</script>


<style>

    .hideUpload .el-upload {
        display: none; /* 上传按钮隐藏 */
    }

    .hideUploadTip .el-upload__tip {
        display: none; /* 上传提示隐藏 */
    }

    .el-upload-list__item-actions {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        cursor: default;
        text-align: center;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0, 0, 0, .5);
        transition: opacity .3s;
    }

    .el-upload-list__item-actions::after {
        display: inline-block;
        content: "";
        height: 100%;
        vertical-align: middle
    }

    .el-upload-list__item-actions span {
        display: none;
        cursor: pointer;
    }

    .el-upload-list__item-actions span + span {
        margin-left: 15px;
    }

    .el-upload-list__item-actions:hover {
        opacity: 1;
    }

    .el-upload-list__item-actions:hover span {
        display: inline-block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar-layout {
        position: relative;
    }

    .avatar {
        width: 146px;
        height: 146px;
        display: block;
    }

    .avatar-view {
        width: 120px;
        height: 120px;
        display: block;
    }

</style>
